package com.saltedfish.tool.ui.flag

import android.Manifest
import android.os.Bundle
import android.os.Handler
import android.text.TextUtils
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import cn.droidlover.xdroidmvp.base.SimpleListener
import cn.droidlover.xdroidmvp.event.BusProvider
import cn.droidlover.xdroidmvp.popwindow.AlertButtonDialog
import cn.droidlover.xdroidmvp.util.AppUtil
import cn.droidlover.xdroidmvp.util.ToastUtils
import com.blankj.rxbus.RxBus
import com.saltedfish.tool.R
import com.saltedfish.tool.dao.*
import com.saltedfish.tool.dialog.UICreateFlagDialog
import com.saltedfish.tool.dialog.UICreateSonFlagDialog
import com.saltedfish.tool.dialog.UIFlagDoneDialog
import com.saltedfish.tool.model.FlagTable
import com.saltedfish.tool.model.ModelInfo
import com.saltedfish.tool.model.SmallTable
import com.saltedfish.tool.present.XAP
import com.saltedfish.tool.ui.XActivity
import com.saltedfish.tool.ui.flag.adapter.SelectFlagColorAdapter
import com.saltedfish.tool.ui.flag.adapter.SubFlagAdapter
import com.saltedfish.tool.util.ViewClickUtils
import kotlinx.android.synthetic.main.activity_flag_detail.*

class FlagDetailActivity : XActivity<XAP>(), View.OnClickListener {


    override fun getLayoutId(): Int {
        setStatusColor(true, 1)
        setStatusBlack()
        return R.layout.activity_flag_detail
    }


    private var database: AppDatabase? = null
    private  var subFlagDao : SubFlagModelDao? =null
    private  var flagDao : FlagInfoDao? =null
    private  var dayDBDao : DayDBDao? =null

    private  var flagInfo : FlagTable? =null
    private var flagId: String? = null
    private var subFlagLists: MutableList<SmallTable> = ArrayList()

    private var linearLayoutManager: LinearLayoutManager? = null
    private var adapter: SubFlagAdapter? = null

    private var flagAdapter: SelectFlagColorAdapter? = null

    var colorList: MutableList<Int>? =  ArrayList()

    override fun initData(savedInstanceState: Bundle?) {
        database = AppDataUtils.initRoom(context)

        flagId = intent.getStringExtra("flagId")
        ViewClickUtils.setViewClick(this, tvBack)
        ViewClickUtils.setViewClick(this, tvDeltele)
        ViewClickUtils.setViewClick(this, ivSonFlag)
        ViewClickUtils.setViewClick(this, btn_create_son_flag)
        ViewClickUtils.setViewClick(this, btn_edit_flag)

        colorList!!.add(R.drawable.shape_radius_round_ff68_20)
        colorList!!.add(R.drawable.shape_radius_round_ff9b_20)
        colorList!!.add(R.drawable.shape_radius_round_ffc7_20)
        colorList!!.add(R.drawable.shape_radius_round_a3e9_20)
        colorList!!.add(R.drawable.shape_radius_round_3097_20)
        colorList!!.add(R.drawable.shape_radius_round_ca7a_20)

        mColorRecyclerView.setHasFixedSize(true)
        mColorRecyclerView.layoutManager = GridLayoutManager(context, 6)
       // mColorRecyclerView.layoutManager = LinearLayoutManager(context, RecyclerView.HORIZONTAL, false)
        flagAdapter = SelectFlagColorAdapter(colorList, context)

        mColorRecyclerView.adapter = flagAdapter

        showSonFlagList()

        BusProvider.getBus().subscribe(context,
                RxBus.Callback<ModelInfo> { modelInfo ->

                    if (modelInfo.updateFlag) {
                        showSonFlagList()

                        if(modelInfo.flagDone){
                            initFlagDoneDialog(modelInfo.type,modelInfo.title)
                        }
                    }

                })

    }

    private var uiFlagDoneDialog: UIFlagDoneDialog? = null

    /**
     *  打卡完成弹窗
     */
    private fun initFlagDoneDialog(type: Int, title: String) {

        if (uiFlagDoneDialog == null) {
            uiFlagDoneDialog = UIFlagDoneDialog(context)
        }
        uiFlagDoneDialog!!.updateFlagDone(type, title);
        uiFlagDoneDialog!!.show()
    }

    private fun showSonFlagList() {

        if(database !=null){
            flagDao = database!!.flagInfoDao()
            subFlagDao = database!!.subFlagDao()
            dayDBDao = database!!.dayDBDao()
            flagInfo = flagDao!!.getById(flagId)

            if(flagInfo !=null){
                flagAdapter!!.setSelectPosition(flagInfo!!.color);
                tvFlagTitile.text = flagInfo!!.title
                tvFlagContent.text = flagInfo!!.subTitle

                subFlagLists.clear()
                subFlagLists = subFlagDao!!.getAllByFlagId(flagId)

                if(subFlagLists.size !=0){
                    if(flagInfo!!.isComplete){
                        btn_edit_flag.visibility = View.GONE
                        ivSonFlag.visibility = View.GONE
                    }else{
                        ivSonFlag.visibility = View.VISIBLE
                        btn_edit_flag.visibility = View.VISIBLE
                    }
                    tvNosan.visibility = View.GONE
                    btn_create_son_flag.visibility = View.GONE
                    linearLayoutManager = LinearLayoutManager(context)
                    mRecyclerView.layoutManager = linearLayoutManager
                    adapter = SubFlagAdapter(subFlagLists, flagInfo!!.color, 1)
                    mRecyclerView.adapter = adapter
                }else{
                    ivSonFlag.visibility = View.GONE
                    tvNosan.visibility = View.VISIBLE
                    btn_create_son_flag.visibility = View.VISIBLE
                }
            }
        }

    }

    override fun newP(): XAP? {
        return null
    }



    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.tvBack -> {
                finish()
            }
            R.id.tvDeltele -> {
                deleteFlagDialog()
            }
            R.id.ivSonFlag -> {
                initCreateSonFalgView()
            }
            R.id.btn_create_son_flag -> {
                initCreateSonFalgView()
            }
            R.id.btn_edit_flag -> {
                checkStoragePermission()
            }

        }
    }

    private var  createSonFlagDialog : UICreateSonFlagDialog? =null
    private var  createFlagDialog : UICreateFlagDialog? =null
    private val mHandler = Handler()


    //检查相关权限
    private fun checkStoragePermission() {
        if (
            rxPermissions.isGranted(Manifest.permission.READ_CALENDAR)
            && rxPermissions.isGranted(Manifest.permission.WRITE_CALENDAR)
            && rxPermissions.isGranted(Manifest.permission.READ_EXTERNAL_STORAGE)
            && rxPermissions.isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE)
        ) {
            initCreateFalgView()
        } else {
            rxPermissions.request(
                Manifest.permission.READ_CALENDAR,
                Manifest.permission.WRITE_CALENDAR,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
            ).subscribe { t ->
                if (t) {
                    initCreateFalgView()
                }
            }.isDisposed
        }

    }

    /**
     * 创建Flag
     */
    private fun initCreateFalgView() {

//        if (createFlagDialog == null) {
            createFlagDialog = UICreateFlagDialog(context, database)
            createFlagDialog!!.setSimpleListener(object : SimpleListener<Int>() {
                override fun onClick(type: String) {
//                    if (type == "save") {
//                        initDataShow()
//                        createFlagDialog!!.dismiss()
//                    }
                }
            })
//        }

        if(!TextUtils.isEmpty(flagId)){
            createFlagDialog!!.updateFlag(flagId)
        }
        createFlagDialog!!.setOnKeyBackListener(false)

        createFlagDialog!!.show()

        mHandler.postDelayed({
            AppUtil.showSoftInput(context)
        }, 500)

    }

    /**
     * 创建子目标
     */
    private fun initCreateSonFalgView() {

//        if (createSonFlagDialog == null) {
            createSonFlagDialog = UICreateSonFlagDialog(context, flagId, database)
            createSonFlagDialog!!.setSimpleListener(object : SimpleListener<Int>() {
                override fun onClick(type: String) {

                }
            })
//        }
        createSonFlagDialog!!.setOnKeyBackListener(false)

        createSonFlagDialog!!.show()

        mHandler.postDelayed(Runnable {
            AppUtil.showSoftInput(context)
        }, 500)


    }

    /**
     * 删除弹窗
     */
    private fun deleteFlagDialog() {
        val dialog = AlertButtonDialog(context)
        dialog.builder()
        dialog.setTitle("删除Flag")
        dialog.setMsg("该Flag及其子目标和完成记录都将被删除,\n" +
                "确认要删除吗？")
        dialog.setPositiveButton("确认"
        ) {  deleteFlag() }
        dialog.setNegativeButton("取消"
        ) { }
        dialog.show()
    }

    private fun deleteFlag() {
        if(flagDao !=null){
             flagDao!!.deleteFlagById(flagInfo!!.flagId)
             subFlagDao!!.deleteAllByFId(flagInfo!!.flagId)
             dayDBDao!!.deleteDayTableByFId(flagInfo!!.flagId)
            var modelInfo = ModelInfo()
            modelInfo.updateFlag = true
            modelInfo.updateCalendar2 = true
            BusProvider.getBus().post(modelInfo)

            finish()
        }

    }


}
